package com.qumitech.visualnovel.component.util;

import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Created by Edison.hu on 18/12/17.
 */
@Component
public class ExcelHandler {

    public void openExcel(HttpServletResponse response, String filePath) {
        String suffix = filePath.substring(filePath.lastIndexOf("/") + 1);
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        try {
            response.setHeader("Content-disposition", "attachment;filename=" + new String(suffix.getBytes("utf-8"), "iso-8859-1"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        try {
            OutputStream os = response.getOutputStream();

            FileInputStream fis = new FileInputStream(filePath);
            byte[] buffer = new byte[1024];
            BufferedInputStream bis = new BufferedInputStream(fis);
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer);
                i = bis.read(buffer);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //根据输入的表头字符串生成excel表头和样式
    //输入的表头列用 , 分割
    public HSSFSheet writeExcelHead(HSSFWorkbook workbook, String sheetName, String head) {

        //设置表头格式
        HSSFSheet sheet = workbook.createSheet(sheetName);
        HSSFCellStyle setBorder = workbook.createCellStyle();
        setBorder.setFillForegroundColor((short) 13);// 设置背景色
        setBorder.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        setBorder.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中

        //设置表头
        String[] headList = head.split(",");
        HSSFRow row0 = sheet.createRow(0);
        HSSFCell cell = null;
        for (int i = 0; i < headList.length; i++) {
            cell = row0.createCell(i);
            cell.setCellValue(headList[i]);
            cell.setCellStyle(setBorder);
        }

        return sheet;
    }
}